namespace Tycho.Parser.Peg {
    public static class ProductionExtensions {
        public static ITerm ParseTerm (this IProduction production, string source) {
            return production.ParseTerm (source, null);
        }

        public static ITerm ParseTerm (this IProduction production, string source, string filename) {
            return production.ParseTerm (source, new ParseContext (), new ParseEnvironment (filename));
        }

        public static ITerm ParseTerm (this IProduction production, string source, string filename, IDynamicGrammar dynamicGrammar) {
            return production.ParseTerm (source, new ParseContext (dynamicGrammar), new ParseEnvironment (filename));
        }

        private static ITerm ParseTerm (this IProduction production, string source, ParseContext context, ParseEnvironment parseEnvironment) {
            char[] sourceChars = source.ToCharArray ();

            ParseResult result = production.Parse (sourceChars, 0, context, source, parseEnvironment);
            if (result != null) {
                int endIndex = Whitespace.SkipWhitespaceAndNewLines (sourceChars, result.Index);
                if (endIndex == sourceChars.Length) {
                    return result.Term;
                }
            }

            parseEnvironment.SyntaxErrors.CommitError (null);
            throw new SyntaxException (null, parseEnvironment.SyntaxErrors.SyntaxErrors);
        }

        public static ParseResult Parse (this IProduction production, string source) {
            return production.Parse (source.ToCharArray(), 0, new ParseContext (), source, new ParseEnvironment (null));
        }
    }
}